package net.kazed.nextaction.context.activity;

import java.util.Calendar;
import java.util.GregorianCalendar;

import net.kazed.nextaction.ApplicationResource;
import net.kazed.nextaction.NextActionApplication;
import net.kazed.nextaction.R;
import net.kazed.nextaction.database.Task;
import net.kazed.nextaction.database.TaskStatus;
import net.kazed.nextaction.process.StartDateProcessor;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

public class StartedTasksActivity extends ListActivity {

   private static final int MENU_SELECT_DAY = Menu.FIRST;
   private static final int MENU_SELECT_WEEK = MENU_SELECT_DAY + 1;
   private static final int MENU_SELECT_MONTH = MENU_SELECT_WEEK + 1;
   
   private static final int VIEW_TASK = 1;
   
   private ApplicationResource applicationResource;
   private Cursor cursor;

	@Override
    public void onCreate(Bundle icicle) {
      NextActionApplication application = (NextActionApplication) getApplication();
      applicationResource = application.getApplicationResource();
	      
      setContentView(R.layout.started_tasks);
      setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);

      SharedPreferences preferences = getPreferences(MODE_WORLD_READABLE);
      int numberOfDays = preferences.getInt("startedTasksPeriod", TaskDatePeriod.DAY.getNumberOfDays());
      createListCursor(numberOfDays);

      super.onCreate(icicle);
	}

	@Override
	protected void onResume() {
		super.onResume();
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                        Service.NOTIFICATION_SERVICE);
        notificationManager.cancel(StartDateProcessor.NOTIFICATION_ID);
	}

    @Override
   protected void onListItemClick(ListView l, View v, int position, long id) {
      Uri itemUri = ContentUris.withAppendedId(Task.CONTENT_URI, id);

      String action = getIntent().getAction();
      if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
         // The caller is waiting for us to return a task selected by
         // the user. They have clicked on one, so return it now.
         Intent intent = new Intent();
         setResult(RESULT_OK, intent);
      } else {
         // Launch activity to view/edit the currently selected item
         Intent intent = new Intent(Intent.ACTION_VIEW, itemUri);
         startActivityForResult(intent, VIEW_TASK);
      }
   }

    @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      Resources resources = getResources();
      menu.add(0, MENU_SELECT_DAY, 0, resources.getString(R.string.menu_select_day))
         .setIcon(android.R.drawable.ic_menu_day)
         .setAlphabeticShortcut('d');
      menu.add(0, MENU_SELECT_WEEK, 0, resources.getString(R.string.menu_select_week))
      .setIcon(android.R.drawable.ic_menu_week)
      .setAlphabeticShortcut('w');
      menu.add(0, MENU_SELECT_MONTH, 0, resources.getString(R.string.menu_select_month))
      .setIcon(android.R.drawable.ic_menu_month)
      .setAlphabeticShortcut('m');
      return super.onCreateOptionsMenu(menu);
   }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int numberOfDays = 0;
       switch (item.getItemId()) {
       case MENU_SELECT_DAY:
           numberOfDays = TaskDatePeriod.DAY.getNumberOfDays();
          break;
       case MENU_SELECT_WEEK:
           numberOfDays = TaskDatePeriod.WEEK.getNumberOfDays();
           break;
       case MENU_SELECT_MONTH:
           numberOfDays = TaskDatePeriod.MONTH.getNumberOfDays();
           break;
       }
       SharedPreferences preferences = getPreferences(MODE_WORLD_WRITEABLE);
       SharedPreferences.Editor editor = preferences.edit();
       editor.putInt("startedTasksPeriod", numberOfDays);
       editor.commit();
       createListCursor(numberOfDays);
       
       return super.onOptionsItemSelected(item);
    }

    /**
     * Create cursor for list view.
     * @param numberOfDays Number of days for selection period of started tasks.
     */
    private void createListCursor(int numberOfDays) {
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.roll(Calendar.DAY_OF_YEAR, -numberOfDays);
        long beginTime = calendar.getTimeInMillis();
        long endTime = System.currentTimeMillis();
        cursor = managedQuery(Task.CONTENT_URI, Task.FULL_PROJECTION.getFieldNames(), Task.Column.STATUS + " = " + TaskStatus.NEXT_ACTION.getType()
                        + " and " + Task.Column.START_DATE + " > ? and " + Task.Column.START_DATE + " < ?",
                        new String[] {Long.toString(beginTime), Long.toString(endTime)},
                        Task.Column.START_DATE + " DESC");
        setListAdapter(new TaskListAdapter(this, cursor, applicationResource));
    }
        
}
